package com.nuc.bigdata.service.impl;

import cn.hutool.core.util.IdUtil;
import com.nuc.bigdata.config.CryptConfig;
import com.nuc.bigdata.exception.BusinessException;
import com.nuc.bigdata.model.ResultCode;
import com.nuc.bigdata.orm.entity.User;
import com.nuc.bigdata.orm.repository.UserRepository;
import com.nuc.bigdata.service.SignUpService;
import com.nuc.bigdata.util.CryptUtils;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.validation.constraints.NotEmpty;

/**
 * @author JackLuo
 * @date 2019/10/31
 */
@Service
public class SignUpServiceImpl implements SignUpService {
    private final UserRepository repository;
    private final CryptConfig cryptConfig;

    @Autowired
    public SignUpServiceImpl(UserRepository repository,CryptConfig cryptConfig){
        this.cryptConfig = cryptConfig;
        this.repository = repository;
    }

    @Override
    @Transactional
    public User signUp(User user) throws Exception {
        String loginName = user.getLoginName();
        User userByLoginName = repository.findUserByLoginName(loginName);
        if(StringUtils.isEmpty(userByLoginName)) {
            // 编译UserId
            String userId = generateUserId();
            user.setUserId(userId);
            // 加密password
            String password = user.getPassword();
            CryptUtils cryptUtils = new CryptUtils(cryptConfig.getKey(),cryptConfig.getAlgorithm() );
            String encryptPassword = cryptUtils.encrypt(password);
            user.setPassword(encryptPassword);
            return repository.save(user);
        }else {
            throw new BusinessException(ResultCode.USER_HAS_EXISTED,user);
        }
    }

    private String generateUserId(){
        return IdUtil.fastSimpleUUID();
    }
}
